<?php

use Mapper\MemberModel as MemberMapper;
use Mapper\FriendcircleModel as FriendCircleMapper;
use Mapper\FriendModel as FriendMapper;
use Mapper\FriendcirclesupportModel as FriendCircleSupportMapper;

class FriendcircleController extends \Base\ApiController {

    /**
     * @desc 朋友圈发布动态
     * @return false
     */
    public function addAction() {
        $request   = $this->getRequest();
        $uid       = \Lib\User::getInstance()->id();
        $content   = (string)$request->get('content');
        $imgUrl    = (string)$request->get('img_url');
        $longitude = (float)$request->get('longitude');
        $latitude  = (float)$request->get('latitude');

        if(empty($content)) {
            return \Response::error('内容不能为空', 10301);
        }

        // 经纬度为空时, 不判断
        if(!empty($longitude) && !empty($latitude) && ($longitude > 180 || $longitude < 0 || $latitude > 90 || $latitude < 0)) {
            return \Response::error('经纬度数据有误, 请重新获取', 10118);
        }

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid);

        if(!$memberModel instanceof \MemberModel) {
            return \Response::error('Invalid Uid', 10110);
        }

        $model  = new \FriendCircleModel();
        $mapper = FriendCircleMapper::getInstance();

        $model->setMember_id($uid);
        $model->setContent($content);
        $model->setImg_url($imgUrl);
        $model->setLongitude($longitude * \Lib\Consts::LATITUDE_LONGITUDE_CONVERSION);
        $model->setLatitude($latitude * \Lib\Consts::LATITUDE_LONGITUDE_CONVERSION);
        $model->setAdd_time(time());
        $model->setStatus(\Lib\Consts::FRIEND_CIRCLE_STATUS_NORMAL);
        $model->setGender($memberModel->getGender());

        try {
            $id = $mapper->insert($model);
            return $id > 0 ? \Response::data(null) : \Response::error('发布失败', 10312);
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @desc 动态详情信息
     *
     * @return false
     */
    public function detailAction() {
        $uid     = \Lib\User::getInstance()->id();
        $request = $this->getRequest();
        $infoId  = (int)$request->get('info_id');

        if($infoId <= 0) {
            return \Response::error('动态信息id有误', 10303);
        }

        $mapper = FriendCircleMapper::getInstance();
        $model  = $mapper->findById($infoId);

        if(!$model instanceof \FriendCircleModel) {
            return \Response::error('无效的朋友圈id', 10302);
        }

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($model->getMember_id());

        if(!$memberModel instanceof \MemberModel) {
            return \Response::error('uid不存在', 10305);
        }

        $data = $model->toArray();

        $birthday = $memberModel->getBirthday();
        $age      = date('Y') - date('Y', $birthday) - 1;

        if(date('m', time()) == date('m', $birthday)) {
            if(date('d', time()) > date('d', $birthday)) {
                ++$age;
            }
        } elseif(date('m', time()) > date('m', $birthday)) {
            ++$age;
        }

        $data['age']      = $age;
        $data['uid']      = $model->getMember_id();
        $data['avatar']   = $memberModel->getAvatar();
        $data['nickname'] = urldecode($memberModel->getNick_name());
        $data['gender']   = $memberModel->getGender();
        // 发布时间
        $time         = $model->getAdd_time();
        $data['time'] = !empty($time) ? date('m月d日 H:i', $time) : '';

        $imgUrl = $model->getImg_url();

        if(empty($imgUrl)) {
            $data['img_url_arr'] = [];
        } elseif(strpos($imgUrl, ',') !== false) {
            $data['img_url_arr'] = explode(',', $imgUrl);
        } else {
            $data['img_url_arr'] = [$imgUrl];
        }

        // 点赞的人
        $supportMapper      = FriendCircleSupportMapper::getInstance();
        $supportModel       = $supportMapper->fetch([
            'friend_id'        => $uid,
            'friend_circle_id' => $infoId,
            'status'           => \Lib\Consts::FRIEND_SUPPORT_NORMAL,
        ]);
        $data['is_support'] = ($supportModel instanceof \FriendCircleSupportModel ? '1' : '2');

        return \Response::data($data, '获取动态信息成功');
    }

    /**
     * @desc 朋友圈动态信息删除
     *
     * @return false
     */
    public function delAction() {
        $request = $this->getRequest();
        $uid     = \Lib\User::getInstance()->id();
        $infoId  = (int)$request->get('info_id', 5);

        if($infoId <= 0) {
            return \Response::error('动态信息id有误', 10303);
        }

        $mapper = FriendCircleMapper::getInstance();
        $model  = $mapper->fetch(['id' => $infoId, 'member_id' => $uid]);

        if(!$model instanceof \FriendCircleModel) {
            return \Response::error('无效的朋友圈id', 10302);
        }

        $data = [
            'status' => \Lib\Consts::FRIEND_CIRCLE_STATUS_DEL,
        ];

        try {
            $rows = $mapper->update($data, ['id' => $infoId]);
            return $rows > 0 ? \Response::data(null) : \Response::error('删除动态信息失败', 10313);
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @desc 点赞
     *
     * @return false
     */
    public function supportAction() {
        $request = $this->getRequest();
        $infoId  = (int)$request->get('info_id');
        $uid     = \Lib\User::getInstance()->id();

        if($infoId <= 0) {
            return \Response::error('动态信息id有误', 10303);
        }

        if(empty($uid)) {
            return \Response::error('登录信息已失效, 请重新登录', 10106);
        }

        // 验证动态信息id
        $mapper = FriendCircleMapper::getInstance();
        $model  = $mapper->findById($infoId);

        if(!$model instanceof \FriendCircleModel) {
            return \Response::error('无效的朋友圈id', 10302);
        }

        // 验证用户uid
        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid);

        if(!$memberModel instanceof \MemberModel) {
            return \Response::error('Invalid Uid', 10110);
        }

        $supportMapper = FriendCircleSupportMapper::getInstance();
        $supportModel  = $supportMapper->fetch(['friend_circle_id' => $infoId, 'friend_id' => $uid]);

        try {
            // 值已存在, 即更新, 不存在则插入
            if($supportModel instanceof \FriendCircleSupportModel) {
                $supportModel->setStatus(\Lib\Consts::FRIEND_SUPPORT_NORMAL);
                $supportModel->setUpdate_time(time());
                $supportMapper->update($supportModel, ['id' => $supportModel->getId()]);
                return \Response::data(null);
            } else {
                $supportModel = new \FriendCircleSupportModel();
                $supportModel->setFriend_id($uid);
                $supportModel->setStatus(\Lib\Consts::FRIEND_SUPPORT_NORMAL);
                $supportModel->setFriend_circle_id($infoId);
                $id = $supportMapper->insert($supportModel);

                if($id > 0) {
                    $imgUrl = $model->getImg_url();

                    if(!empty($imgUrl) || strpos($imgUrl, ',') !== false) {
                        $arr    = explode(',', $imgUrl);
                        $imgUrl = $arr[0];
                    }

                    $msgData = [
                        'info_id'  => $infoId,
                        'avatar'   => $memberModel->getAvatar(),
                        'nickname' => urldecode($memberModel->getNick_name()),
                        'content'  => '赞了您',
                        'img_url'  => $imgUrl, // 此条朋友圈的第一张图片
                        'time'     => date('m月d日 H:s'),
                    ];
                    \Lib\MsgPush::msgadd(\Lib\Consts::MESSAGE_PUSH_FRIEND_CIRCLE, $msgData);
                    return \Response::data(null);
                } else {
                    return \Response::error('点赞失败', 10309);
                }
            }
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @desc 取消点赞
     *
     * @return false
     */
    public function supportCancelAction() {
        $request = $this->getRequest();
        $infoId  = (int)$request->get('info_id');
        $uid     = \Lib\User::getInstance()->id();

        if($infoId <= 0) {
            return \Response::error('动态信息id有误', 10304);
        }

        if(empty($uid)) {
            return \Response::error('登录信息已失效, 请重新登录', 10106);
        }

        // 验证动态信息id
        $mapper = FriendCircleMapper::getInstance();
        $model  = $mapper->findById($infoId);

        if(!$model instanceof \FriendCircleModel) {
            return \Response::error('无效的朋友圈id', 10302);
        }

        // 验证用户uid
        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid);

        if(!$memberModel instanceof \MemberModel) {
            return \Response::error('Invalid Uid', 10110);
        }

        $supportMapper = FriendCircleSupportMapper::getInstance();
        $supportModel  = $supportMapper->fetch(['friend_circle_id' => $infoId, 'friend_id' => $uid]);

        if(!$supportModel instanceof \FriendCircleSupportModel) {
            return \Response::error('Invalid Ids', 10110);
        }

        $supportId = $supportModel->getId();

        if(empty($supportId)) {
            return \Response::error('未点赞过, 不能取消点赞', 10304);
        }

        try {
            $supportModel->setStatus(\Lib\Consts::FRIEND_SUPPORT_CANCEL);
            $supportMapper->update($supportModel, ['id' => $supportId]);
            return \Response::data(null, '取消赞成功');
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @desc 点赞列表
     *
     * @return false
     */
    public function supportlistAction() {
        $request = $this->getRequest();
        $infoId  = (int)$request->get('info_id');

        if($infoId <= 0) {
            return \Response::error('动态信息id有误', 10303);
        }

        // 验证动态信息id
        $mapper = FriendCircleMapper::getInstance();
        $model  = $mapper->findById($infoId);

        if(!$model instanceof \FriendCircleModel) {
            return \Response::error('无效的朋友圈id', 10302);
        }

        $supportMapper = FriendCircleSupportMapper::getInstance();
        $supportModels = $supportMapper->fetchAll([
            'friend_circle_id' => $infoId,
            'status'           => \Lib\Consts::FRIEND_SUPPORT_NORMAL,
        ]);

        if(empty($supportModels)) {
            return \Response::data([]);
        }

        $return = [];

        foreach($supportModels as $supportModel) {
            $data         = $supportModel->toArray();
            $memberMapper = MemberMapper::getInstance();
            $memberModel  = $memberMapper->findById($supportModel->getFriend_id());

            if(!$memberModel instanceof \MemberModel) {
                return \Response::error('无效的uid', 10311);
            }

            $data['avatar'] = $memberModel->getAvatar();
            $return[]       = $data;
        }

        return \Response::data($return);
    }

    /**
     * @desc 我的朋友圈列表
     *
     * @return false
     */
    public function listAction() {
        $uid          = \Lib\User::getInstance()->id();
        $uid          = 65535;
        $request      = $this->getRequest();
        $page         = (int)$request->get('page', 1);
        $perPage      = (int)$request->get('per_page', 10);
        $page         = max(1, $page);
        $perPage      = min(30, $perPage);
        $limit        = $perPage;
        $offset       = $limit * ($page - 1);
        $ids[0]       = $uid;
        $return       = [];
        $friendMapper = FriendMapper::getInstance();
        $friendModels = $friendMapper->fetchAll(['member_id' => $uid]);

        // 取得我的好友id
        foreach($friendModels as $friendModel) {
            $ids[] = $friendModel->getFriend_id();
        }

        // 取得对应的动态信息
        $friendCircleMapper = FriendCircleMapper::getInstance();
        $models             = $friendCircleMapper->fetchAll(['member_id' => $ids], 'add_time DESC', $limit, $offset);
        $memberMapper       = MemberMapper::getInstance();
        $supportMapper      = FriendCircleSupportMapper::getInstance();

        foreach($models as $model) {
            $data = $model->toArray();
            // 取得头像, 是否点赞
            $memberModel = $memberMapper->findById($model->getMember_id());

            if(!$memberModel instanceof \MemberModel) {
                return \Response::error('无效的uid', 10311);
            }

            $birthday = $memberModel->getBirthday();
            $age      = date('Y') - date('Y', $birthday) - 1;

            if(date('m', time()) == date('m', $birthday)) {
                if(date('d', time()) > date('d', $birthday)) {
                    ++$age;
                }
            } elseif(date('m', time()) > date('m', $birthday)) {
                ++$age;
            }

            $data['age']      = $age;
            $data['avatar']   = $memberModel->getAvatar();
            $data['nickname'] = urldecode($memberModel->getNick_name());
            $data['gender']   = $memberModel->getGender();

            $supportModel = $supportMapper->fetch([
                'friend_id'        => $uid,
                'friend_circle_id' => $model->getId(),
                'status'           => \Lib\Consts::FRIEND_SUPPORT_NORMAL,
            ]);

            $data['is_support'] = ($supportModel instanceof \FriendCircleSupportModel ? '1' : '2');
            // 发布时间->今天显示时间, 否则显示日期
            $time         = $model->getAdd_time();
            $data['time'] = (date('Y-m-d') === date('Y-m-d', $time)) ? date('H:i', $time) : date('m月d日', $time);

            $imgUrl = $model->getImg_url();

            if(empty($imgUrl)) {
                $data['img_url_arr'] = [];
            } elseif(strpos($imgUrl, ',') !== false) {
                $data['img_url_arr'] = explode(',', $imgUrl);
            } else {
                $data['img_url_arr'] = [$imgUrl];
            }

            $return['data'][] = $data;
        }

        $return['msg_len'] = \Lib\MsgPush::msglen(\Lib\Consts::MESSAGE_PUSH_FRIEND_CIRCLE);
        $ownMemberModel    = $memberMapper->findById($uid);
        $return['avatar']  = ($ownMemberModel instanceof \MemberModel ? $ownMemberModel->getAvatar() : '');

        return \Response::data($return);
    }

    /**
     * @desc 附近朋友圈列表
     *
     * @return false
     */
    public function nearbylistAction() {
        $uid     = \Lib\User::getInstance()->id();
        $request = $this->getRequest();
        $page    = (int)$request->get('page', 1);
        $perPage = (int)$request->get('per_page', 10);
        $gender  = (int)$request->get('gender');
        $page    = max(1, $page);
        $perPage = min(30, $perPage);
        $limit   = $perPage;
        $offset  = $limit * ($page - 1);
        $return  = [];

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid);

        if(!$memberModel instanceof \MemberModel) {
            return \Response::error('无效的uid', 10311);
        }

        $longitude = $memberModel->getLongitude();
        $latitude  = $memberModel->getlatitude();

        if($longitude < 0 || $latitude < 0 || $longitude > 180 || $latitude > 90) {
            return \Response::error('经纬度数据有误, 请重新获取', 10118);
        }

        $circleMapper = FriendCircleMapper::getInstance();

        $llValue    = \Lib\Consts::LATITUDE_LONGITUDE_1KM;
        $conversion = \Lib\Consts::LATITUDE_LONGITUDE_CONVERSION;

        $where = [
            'status'         => \Lib\Consts::FRIEND_CIRCLE_STATUS_NORMAL,
            'longitude <= ?' => $longitude * $conversion + $llValue,
            'longitude >= ?' => $longitude * $conversion - $llValue,
            'latitude <= ?'  => $latitude * $conversion + $llValue,
            'latitude >= ?'  => $latitude * $conversion - $llValue,
        ];

        if($gender === 1 || $gender === 2) {
            $where['gender'] = $gender;
        }

        $models = $circleMapper->fetchAll($where, 'id', $limit, $offset);

        if(empty($models)) {
            return \Response::data([]);
        }

        $supportMapper = FriendCircleSupportMapper::getInstance();

        foreach($models as $model) {
            $data             = $model->toArray();
            $longitudeTo      = $model->getLongitude() / $conversion;
            $latitudeTo       = $model->getLatitude() / $conversion;
            $distance         = $this->getDistance($longitude, $latitude, $longitudeTo, $latitudeTo);
            $data['distance'] = $distance;
            $distanceArr[]    = $distance;

            // 取得头像, 是否点赞
            $memberModel = $memberMapper->findById($model->getMember_id());

            if(!$memberModel instanceof \MemberModel) {
                return \Response::error('无效的uid', 10311);
            }

            $birthday = $memberModel->getBirthday();
            $age      = date('Y') - date('Y', $birthday) - 1;

            if(date('m', time()) == date('m', $birthday)) {
                if(date('d', time()) > date('d', $birthday)) {
                    ++$age;
                }
            } elseif(date('m', time()) > date('m', $birthday)) {
                ++$age;
            }

            $data['age']      = $age;
            $data['avatar']   = $memberModel->getAvatar();
            $data['nickname'] = urldecode($memberModel->getNick_name());
            $data['gender']   = $memberModel->getGender();

            $supportModel       = $supportMapper->fetch(['friend_id' => $uid, 'friend_circle_id' => $model->getId()]);
            $data['is_support'] = ($supportModel instanceof \FriendCircleSupportModel ? '1' : '2');
            // 发布时间->今天显示时间, 否则显示日期
            $time         = $model->getAdd_time();
            $data['time'] = (date('Y-m-d') === date('Y-m-d', $time)) ? date('H:i', $time) : date('m月d日', $time);

            $imgUrl = $model->getImg_url();

            if(empty($imgUrl)) {
                $data['img_url_arr'] = [];
            } elseif(strpos($imgUrl, ',') !== false) {
                $data['img_url_arr'] = explode(',', $imgUrl);
            } else {
                $data['img_url_arr'] = [$imgUrl];
            }

            $return['data'][] = $data;
        }

        array_multisort($distanceArr, SORT_ASC, $return['data']);
        $return['msg_len'] = \Lib\MsgPush::msglen(\Lib\Consts::MESSAGE_PUSH_FRIEND_CIRCLE);
        $ownMemberModel    = $memberMapper->findById($uid);
        $return['avatar']  = ($ownMemberModel instanceof \MemberModel ? $ownMemberModel->getAvatar() : '');

        return \Response::data($return);
    }

    /**
     * @desc 消息列表
     *
     * @param int $page
     * @param int $perPage
     * @return false
     */
    public function msglistAction() {
        $request = $this->getRequest();
        $page    = (int)$request->get('page');
        $perPage = (int)$request->get('per_page');
        $return  = \Lib\MsgPush::msglist(\Lib\Consts::MESSAGE_PUSH_FRIEND_CIRCLE, $page, $perPage);
        // 删除消息
        \Lib\MsgPush::msgdel(\Lib\Consts::MESSAGE_PUSH_FRIEND_CIRCLE);

        return \Response::data($return);
    }

    /**
     * @desc 根据两点间的经纬度计算距离
     * @param $lng1 float 经度值
     * @param $lat1 float 纬度值
     * @param $lng2 float
     * @param $lat2 float
     * @return float
     */
    public function getDistance($lng1, $lat1, $lng2, $lat2) {
        $earthRadius = \Lib\Consts::EARTH_RADIUS;
        $lat1        = ($lat1 * pi()) / 180;
        $lng1        = ($lng1 * pi()) / 180;
        $lat2        = ($lat2 * pi()) / 180;
        $lng2        = ($lng2 * pi()) / 180;

        $calcLongitude      = $lng2 - $lng1;
        $calcLatitude       = $lat2 - $lat1;
        $stepOne            = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo            = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);
    }

    /**
     * @desc 我的发布的动态信息列表
     *
     * @return false
     */
    public function mylistAction() {
        $uid     = \Lib\User::getInstance()->id();
        $request = $this->getRequest();
        $page    = (int)$request->get('page', 1);
        $perPage = (int)$request->get('per_page', 10);
        $page    = max(1, $page);
        $perPage = min(30, $perPage);
        $limit   = $perPage;
        $offset  = $limit * ($page - 1);
        $return  = [];

        // 取得对应的动态信息
        $friendCircleMapper = FriendCircleMapper::getInstance();
        $models             = $friendCircleMapper->fetchAll(['member_id' => $uid], 'add_time DESC', $limit, $offset);
        $memberMapper       = MemberMapper::getInstance();

        foreach($models as $model) {
            $data         = $model->toArray();
            $data['time'] = date('m月d日', $model->getAdd_time());

            $imgUrl = $model->getImg_url();

            if(empty($imgUrl)) {
                $data['img_url_arr'] = [];
            } elseif(strpos($imgUrl, ',') !== false) {
                $data['img_url_arr'] = explode(',', $imgUrl);
            } else {
                $data['img_url_arr'] = [$imgUrl];
            }

            $date = date('m月d日', $model->getAdd_time());

            $tmp['date']   = $date;
            $tmp['data'][] = $data;

            if(isset($return['data'][$date])) {
                $return['data'][$date]['data'][] = $data;
            } else {
                $return['data'][$date] = $tmp;
            }

            unset($tmp);
        }

        if(isset($return['data'])) {
            $return['data'] = array_values($return['data']);
        }

        $ownMemberModel = $memberMapper->findById($uid);

        if(!$ownMemberModel instanceof \MemberModel) {
            $return['avatar']    = '';
            $return['nick_name'] = '';
        } else {
            $return['avatar']    = $ownMemberModel->getAvatar();
            $return['nick_name'] = urldecode($ownMemberModel->getNick_name());
        }

        return \Response::data($return);
    }


}
